package com.ruoyi.common.dao.impl;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional;

import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import com.ruoyi.common.dao.service.BaseAppDAO;

/**
 * @author 坚持到底gl
 * @create 2017-09-26 10:36
 * @desc
 **/
@Repository
public class BaseAppDAOimpl implements BaseAppDAO {

	private static final Logger log = LoggerFactory.getLogger(BaseAppDAOimpl.class);

	@PersistenceContext
	private EntityManager entityManager;

	@Transactional
	@Override
	public boolean save(Object entity) {
		boolean flag = false;
		try {
			entityManager.persist(entity);
			flag = true;
		} catch (Exception e) {
			log.error("---------------保存出错---------------");
			throw e;
		}
		return flag;
	}

	@Transactional
	@Override
	public Object findByid(Class o, Long id) {
		return entityManager.find(o, id);
	}

	@Transactional
	@Override
	public List findBysql(String tablename, String filed, Object o) {
		String sql = "from " + tablename + " u WHERE u." + filed + "=?";
		log.error(sql + "--------sql语句-------------");
		Query query = entityManager.createQuery(sql);
		query.setParameter(1, o);
		List list = query.getResultList();
		entityManager.close();
		return list;
	}

	@Override
	public Object findObjiectBysql(String tablename, String filed, Object o) {
		String sql = "from " + tablename + " u WHERE u." + filed + "=?";
		log.error(sql + "--------sql语句-------------");
		Query query = entityManager.createQuery(sql);
		query.setParameter(1, o);

		entityManager.close();
		return query.getSingleResult();
	}

	@Transactional
	@Override
	public List findByMoreFiled(String tablename, LinkedHashMap<String, Object> map) {
		String sql = "from " + tablename + " u WHERE ";
		Set<String> set = null;
		set = map.keySet();
		List<String> list = new ArrayList<>(set);
		List filedlist = new ArrayList<>();
		for (String filed : list) {
			sql += "u." + filed + "=? and ";
			filedlist.add(filed);
		}
		sql = sql.substring(0, sql.length() - 4);
		log.error(sql + "--------sql语句-------------");
		Query query = entityManager.createQuery(sql);
		for (int i = 0; i < filedlist.size(); i++) {
			query.setParameter(i + 1, map.get(filedlist.get(i)));
		}
		List listRe = query.getResultList();
		entityManager.close();
		return listRe;
	}

	@Transactional
	@Override
	public List findByMoreFiledpages(String tablename, LinkedHashMap<String, Object> map, int start,
			int pageNumber) {
		String sql = "from " + tablename + " u WHERE ";
		Set<String> set = null;
		set = map.keySet();
		List<String> list = new ArrayList<>(set);
		List filedlist = new ArrayList<>();
		for (String filed : list) {
			sql += "u." + filed + "=? and ";
			filedlist.add(filed);
		}
		sql = sql.substring(0, sql.length() - 4);
		log.error(sql + "--------sql语句-------------");
		Query query = entityManager.createQuery(sql);
		for (int i = 0; i < filedlist.size(); i++) {
			query.setParameter(i + 1, map.get(filedlist.get(i)));
		}
		query.setFirstResult((start - 1) * pageNumber);
		query.setMaxResults(pageNumber);
		List listRe = query.getResultList();
		entityManager.close();
		return listRe;
	}

	@Transactional
	@Override
	public List findpages(String tablename, String filed, Object o, int start, int pageNumer) {
		String sql = "from " + tablename + " u WHERE u." + filed + "=?";
		log.error(sql + "--------page--sql语句-------------");
		List list = new ArrayList<>();
		try {
			Query query = entityManager.createQuery(sql);
			query.setParameter(1, o);
			query.setFirstResult((start - 1) * pageNumer);
			query.setMaxResults(pageNumer);
			list = query.getResultList();
			entityManager.close();
		} catch (Exception e) {
			log.error("------------分页错误---------------");
		}

		return list;
	}

	@Transactional
	@Override
	public boolean update(Object entity) {
		boolean flag = false;
		try {
			entityManager.merge(entity);
			flag = true;
		} catch (Exception e) {
			log.error("---------------更新出错---------------");
		}
		return flag;
	}

	@Transactional
	@Override
	public Integer updateMoreFiled(String tablename, LinkedHashMap<String, Object> map) {
		String sql = "UPDATE " + tablename + " AS u SET ";
		Set<String> set = null;
		set = map.keySet();
		List<String> list = new ArrayList<>(set);
		for (int i = 0; i < list.size() - 1; i++) {
			if (map.get(list.get(i)).getClass().getTypeName() == "java.lang.String") {
				log.error("-*****" + map.get(list.get(i)) + "------------" + list.get(i));
				sql += "u." + list.get(i) + "='" + map.get(list.get(i)) + "' , ";
			} else {
				sql += "u." + list.get(i) + "=" + map.get(list.get(i)) + " , ";
			}
		}
		sql = sql.substring(0, sql.length() - 2);
		sql += "where u.id=? ";
		log.error(sql + "--------sql语句-------------");
		int resurlt = 0;
		try {
			Query query = entityManager.createQuery(sql);
			query.setParameter(1, map.get("id"));
			resurlt = query.executeUpdate();
		} catch (Exception e) {
			log.error("更新出错-----------------------");
			e.printStackTrace();

		}
		return resurlt;
	}

	@Transactional
	@Override
	public boolean delete(Object entity) {
		boolean flag = false;
		try {
			entityManager.remove(entityManager.merge(entity));
			flag = true;
		} catch (Exception e) {
			log.error("---------------删除出错---------------");
		}
		return flag;
	}

	@Override
	public Object findCount(String tablename, LinkedHashMap<String, Object> map) {
		String sql = "select count(u) from " + tablename + " u WHERE ";
		Set<String> set = null;
		set = map.keySet();
		List<String> list = new ArrayList<>(set);
		List filedlist = new ArrayList<>();
		for (String filed : list) {
			sql += "u." + filed + "=? and ";
			filedlist.add(filed);
		}
		sql = sql.substring(0, sql.length() - 4);
		log.error(sql + "--------sql语句-------------");
		Query query = entityManager.createQuery(sql);
		for (int i = 0; i < filedlist.size(); i++) {
			query.setParameter(i + 1, map.get(filedlist.get(i)));
		}
		return query.getSingleResult();
	}

	@Override
	public List createNativeQuery(String sql, Class BaseEntity) {
		Query query = entityManager.createNativeQuery(sql, BaseEntity);
		List list = query.getResultList();
		entityManager.close();

		return list;
	}

	@Override
	public List createNativeQuery(String sql) {
		Query query = entityManager.createNativeQuery(sql);
		query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		List list = query.getResultList();
		
		entityManager.close();

		return list;
	}

	@Override
	public Object getSingleResult(String sql, Class BaseEntity) {
		Query query = entityManager.createNativeQuery(sql, BaseEntity);
		 if(query.getResultList().size()==0 ){
			 	entityManager.close();
	            return null;
	        }else{
	        	entityManager.close();
	            return query.getSingleResult();
	        }

	}
}